<template>
	<view class="page">
		<view v-for="(item, key) in result" >
			<view class="img_date">{{ key }}</view>
			<view class="choose_img_list">
				<view v-for="(item1, key1) in item">
					<view class="choose_img_list_item" @longpress="caItem(item1)">
						<image class="choose_img_list_item_img" @click.stop="prevImg(item1.picturePath)"
							:src="item1.picturePath">
						</image>
					 
						<view class="btn_del" @click="deletePicture(item1)" v-if="item1.ca">
							<u-icon size="22" name="trash" color="#fff"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="footer" v-if="hasTure">
			<view class="footer_1">
				<view class="footer_1_left">最多上传3张照片</view>
				<view class="footer_1_right">
					<view class="footer_1_right_upload" @click="zdyUpload">上传</view>
					<view class="footer_1_right_hc" @click="hcPhoto">照片生成</view>
				</view>
			</view>

			<u-upload :fileList="fileList1" ref="uploadRef" @afterRead="afterRead" @delete="deletePic" name="1" multiple
				:maxCount="3">
			</u-upload>

			<!-- <view class="footer_2">
				<view class="footer_2_line"></view>
			</view> -->
		</view>

		<u-modal :show="showDel" title="温馨提示" :showConfirmButton="true" @confirm="confirmDel" @cancel="showDel = false"
			:showCancelButton="true" content="确认删除吗?删除后不可恢复!"></u-modal>
	</view>
</template>

<script>
	import {
		api,
		imgDomain
	} from "@/config/common.js";
	export default {
		data() {
			return {
				showDel: false,
				statusBarHeight: "0",
				navHeight: "44",
				fileList1: [],
				uid: "",
				result: [],
				hasTure: false,
				time: null,
				delItem: {},
			};
		},
		components: {},
		filters: {},
		mounted() {},
		onLoad(e) {
			 // uni.setStorageSync("uid", 2);
			// if (e.id){
			// 	uni.setStorageSync('uid',e.id)
			// 	this.getList(uni.getStorageSync('uid'))
			// 	this.hasTure = true
			// } else {
			// 	this.hasTure = false

			// uni.setStorageSync("uid", 2);
			// }
			//公众号授权获取code
			if (e.code) {
				this.getOpenid(e.code);
				return;
			}
			if (uni.getStorageSync("uid")) {
				this.getList(uni.getStorageSync("uid"));
			} else {
				this.wechatLogin();
			}
		},
		onShow() {},
		onPullDownRefresh() {
			this.result = [];
			this.getList(this.uid);
		},
		beforeDestroy() {},
		methods: {
			caItem(e) { 
				e.ca = !e.ca 
			},
			wechatLogin() {
				const appId = "wxb803538cfaa8464f"; // 确保这里填写正确
				const redirectUrl = encodeURIComponent(
					"http://h5.aizizhuzhaoxiangji.com"
				); // 确保这个地址是服务器可以处理的地址
				const scope = "snsapi_userinfo"; // 根据需要选择作用域
				const state = "STATE"; // 可以是任意字符串，用于防止CSRF攻击，并在回调时原样返回
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
			},
			confirmDel() {
				uni.showLoading({});
				api
					.post("/api/user-picture/batch-delete", [this.delItem.id])
					.then((res) => {
						uni.hideLoading();
						if (res.statusCode == 200) {
							this.showDel = false
							uni.$u.toast('删除成功')
							this.getList()
						} else {
							uni.$u.toast('删除失败')
						}
					})
					.catch((err) => {
						uni.hideLoading();
					});
				this.showDel = false;
			},
			deletePicture(e) {
				this.delItem = e;
				this.showDel = true;
			},
			prevImg(path) { 
				uni.previewImage({
					urls: [path],
				});
			},
			hcPhoto() {
				let photos = this.fileList1.map((item) => item.url);
				if (photos.length <= 0) {
					uni.$u.toast("请上传照片");
					return;
				}
				uni.showLoading({
					title: "照片合成中...",
				});
				api
					.post("/api/order/user-picture", {
						userId: uni.getStorageSync("uid"),
						picturePaths: photos,
					})
					.then((res) => {
						let rst = res.data;
						if (rst.statusCode == 200) {
							uni.hideLoading();
							uni.$u.toast("照片合成成功，请去终端选择照片");
							this.fileList1 = [];
						} else {
							uni.hideLoading();
							uni.$u.toast("照片合成失败");
						}
					})
					.catch((err) => {
						uni.hideLoading();
					});
			},
			getOpenid(code) {
				uni.showLoading({});
				api
					.get("/api/we-chat/open-id-by-code/" + code)
					.then((res) => {
						let rst = res.data;
						if (rst.statusCode == 200) {
							this.uid = rst.data.id;
							uni.setStorageSync("uid", rst.data.id);
							this.getList(rst.data.id);
							uni.hideLoading();
						} else {
							uni.hideLoading();
							// uni.$u.toast('登录失败');
						}
					})
					.catch((err) => {
						uni.hideLoading();
					});
			},
			getHasOrder(uid) {
				// uni.showLoading({})
				api
					.get("/api/order/has-order/" + uid)
					.then((res) => {
						let rst = res.data;
						console.log(rst)
						if (rst.statusCode == 200) {
							this.hasTure = rst.data;

						} else {

						}
					})
					.catch((err) => {

					});
			},
			zdyUpload() {
				if (this.fileList1.length >= 3) {
					uni.$u.toast("最多上传3张照片");
				} else {
					this.$refs.uploadRef.chooseFile();
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {  
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url, event) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: "https://api.aizizhuzhaoxiangji.com/api/upload-file/upload-file", // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							Authorization: "BEC127E4D62348058067644E3B8B3CE3", // 假设你有一个存储token的地方
						},
						FileType: "image",
						name: "fileInput",
						formData: {},
						success: (res) => {
							let t_rest = JSON.parse(res.data);
							if (t_rest.statusCode == 200) {
								resolve(t_rest.data[0].Url);
							} else {
								uni.$u.toast("照片上传失败");
								that.deletePic(event);
							}
						},
						fail() {
							that.deletePic(event);
							uni.$u.toast("照片上传失败");
						},
					});
				});
			},
			//获取列表
			getList(uid) {
				// uni.showLoading({})
				api
					.post("/api/user-picture/paid-picture-list", {
						userId: uni.getStorageSync("uid"),
					})
					.then((res) => {
						uni.stopPullDownRefresh();
						// uni.hideLoading()
						let rst = res.data;
						if (rst.statusCode == 200) { 
							
							rst.data.forEach(function(e) {
								e.ca = false
								e.date = e.createdTime
									.split(/[\s:-]/)
									.slice(0, 3)
									.join("-");
							});
							let groupedData = rst.data.reduce((acc, item) => {
								const date = item.date;
								if (!acc[date]) {
									acc[date] = [];
								}
								acc[date].push(item);
								return acc;
							}, {});

							//根据date倒叙排序
							let sortedKeys = Object.keys(groupedData).sort((a, b) => {
								return new Date(b) - new Date(a);
							});
							//根据date倒叙排序
							let sortedData = sortedKeys.reduce((acc, key) => {
								acc[key] = groupedData[key];
								return acc;
							}, {});
							this.result = sortedData;

							//定时器
							this.time = setInterval(() => {
								this.getHasOrder(uni.getStorageSync("uid"));
							}, 2000);
						}
					})
					.catch((err) => {
						uni.stopPullDownRefresh();
						uni.hideLoading();
					});
			},
		},
	};
</script>

<style lang="scss" scoped>
	::v-deep .u-upload__button {
		display: none;
	}

	::v-deep .u-upload__wrap {
		padding-left: 40rpx;
		margin-bottom: 20rpx;
	}

	::v-deep .u-upload__wrap__preview__image {
		width: 160rpx !important;
		height: 160rpx !important;
	}

	.footer {
		.footer_2 {
			height: 68rpx;
			display: flex;
			flex-direction: row;
			// align-items: center;
			justify-content: center;
			padding-top: 40rpx;
			width: 100%;
		}

		// .footer_2_line {
		// 	width: 268rpx;
		// 	height: 10rpx;
		// 	background: #FFFFFF;
		// 	border-radius: 200rpx 200rpx 200rpx 200rpx;
		// }

		.footer_1_right_hc {
			width: 200rpx;
			height: 80rpx;
			background: linear-gradient(90deg, #ff12d2 0%, #6912ff 100%);
			box-shadow: 0rpx 0rpx 13rpx 2rpx rgba(255, 18, 210, 0.24);
			border-radius: 51rpx 51rpx 51rpx 51rpx;

			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #ffffff;

			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
		}

		.footer_1 {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 40rpx;
			min-height: 112rpx;
		}

		.footer_1_right {
			display: flex;
			flex-direction: row;
			align-items: center;
		}

		.footer_1_right_upload {
			// border-radius 未生效可能是因为 border-image 的影响，将 border 拆分为 border-style 和 border-width，并使用 background-image 替代 border-image
			width: 140rpx;
			height: 80rpx;
			box-shadow: 0rpx 0rpx 13rpx 2rpx rgba(255, 18, 210, 0.24);
			border-style: solid;
			border-width: 3rpx;
			border-color: transparent;
			background-image: linear-gradient(#171a33, #171a33),
				linear-gradient(90deg, rgba(255, 18, 210, 1), rgba(105, 18, 255, 1));
			background-origin: border-box;
			background-clip: padding-box, border-box;
			border-radius: 51rpx 51rpx 51rpx 51rpx;

			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #ffffff;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			margin-right: 24rpx;
		}

		.footer_1_left {
			width: 197rpx;
			height: 34rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 24rpx;
			color: #b1b1b1;
			text-align: left;
			font-style: normal;
			text-transform: none;
		}

		position: fixed;
		bottom: 0;
		width: 750rpx;
		min-height: 150rpx;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		background: #171a33;
	}

	.img_date {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #ffffff;
		text-align: left;
		font-style: normal;
		text-transform: none;
		margin-left: 55rpx;
		margin-top: 24rpx;
		margin-bottom: 24rpx;
	}

	.choose_img_list {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;

		.choose_img_list_item {
			width: 300rpx;
			height: 300rpx;
			background: #ffffff;
			border-radius: 15rpx 15rpx 15rpx 15rpx;
			// border: 2rpx solid #FFF9D7;
			margin-left: 50rpx;
			margin-bottom: 40rpx;
			position: relative;

			.choose_img_list_item_img {
				width: 300rpx;
				height: 300rpx;
				border-radius: 15rpx 15rpx 15rpx 15rpx;
				border: 2rpx solid #fff9d7;
			}

			.btn_del {
				position: absolute;
				bottom: 0;
				width: 300rpx;
				height: 60rpx;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				display: flex;
				flex-direction: row;
				justify-content: center;
			}
		}
	}

	page {
		background-image: url(@/static/bg@2x.png);
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		 min-height: 100vh;
		// min-height: 100vh;
		// padding-bottom: 167rpx;
	}
</style>